package com.base.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.base.app.util.SpCommon;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class BaseApplication extends Application {

    private static final String TAG = BaseApplication.class.getSimpleName();
    private static Context mContext;
    private static Handler mHandler;
    private static long mMainThreadId;
    private static boolean lastAppForeground = false;
    private static boolean isAppInForeground = false;

    public static boolean isJomoo = false;//适配九牧和小牧

//    private AMapLocationClient aMapLocationClient;

    // 对象
    private Map<String, String> mCacheMap = new HashMap<String, String>();

    private static SpCommon spCommon;

    public static final String BC_IS_FOREGROUND = "jomoo.cloud.base.application.background";
    public static final String DATA_IS_FOREGROUND = "DATA_IS_FOREGROUND";
    public static final String DATA_IS_FOREGROUND_CHANGED = "DATA_IS_FOREGROUND_CHANGED";
    public Timer appBackgroundTimer;

    public Map<String, String> getCacheMap() {
        return mCacheMap;
    }

    public static SpCommon getSpCommon(){
        return spCommon;
    }

    public static Context getContext() {
        return mContext;
    }

    public static Handler getHandler() {
        return mHandler;
    }

    public static long getMainThreadId() {
        return mMainThreadId;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mContext = this.getApplicationContext();
        //初始化存储器
        initSpCommon();
        //高德地图初始化
        initAMap();
        //初始化和风天气
        initHeWeather();
        //初始化bugly
        initBugly();

        // 2.放置一个主线程的Handler
        mHandler = new Handler();

        // 3.得到主线程的Id
        mMainThreadId = android.os.Process.myTid();

        //初始化本地日志
        initJomooLog();

        //监听应用是否在前台
        foregroundListener();
    }

    private void initAMap(){
        //隐私合规检查（必须调用）
//        AMapLocationClient.updatePrivacyShow(this,true,true);
//        AMapLocationClient.updatePrivacyAgree(this,true);

    }

    private void initJomooLog() {
//        CrashHandler.getInstance().init(this);
//        FFLog.setDebug(BuildConfig.DEBUG);
//        FFLog.setLevel(2);
    }

    private void initBugly() {
//        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
//        try {
//            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
//            String versionName = packageInfo.versionName; // 获取版本名称
//            int versionCode = packageInfo.versionCode; // 获取版本号
//            Log.d("Version", "Version Name: " + versionName);
//            Log.d("Version", "Version Code: " + versionCode);
//            if(versionCode>=0){
//                strategy.setAppVersion(versionName);//设置app的版本名
//            }
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        String packageName = getApplicationContext().getPackageName();
//        strategy.setAppPackageName(packageName);//App的包名
//        strategy.setAppChannel("Jomoo");  //设置渠道
//        CrashReport.initCrashReport(getApplicationContext(), "839bb61182", true, strategy);
    }


    //初始化和风天气
    private void initHeWeather(){
        Log.e("BaseApplication", "初始化天气");
//        HeConfig.init("HE2310201707091359", "e7d3d3969455422bb4b08ee8d3115bf2");//和风天气账户初始化（全局执行一次即可）

//        HeConfig.init("HE2311042021041887", "79894c5d98a040d2a4980705c74d68b7");//和风天气账户初始化（全局执行一次即可）
//        HeConfig.switchToDevService();//和风天气切换至开发版服务
        // HeConfig.switchToBizService();//和风天气切换至商业版服务
    }

    private void initSpCommon(){
        spCommon = SpCommon.getInstance(this);
    }

    //监听应用是否在前台
    private void foregroundListener(){
        registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

            @Override
            public void onActivityStarted(Activity activity) {}

            @Override
            public void onActivityResumed(Activity activity) {
                isAppInForeground = true;
                Log.e(TAG, "前台");
                if(appBackgroundTimer!=null){
                    appBackgroundTimer.cancel();
                    appBackgroundTimer = null;
                }
                appBackgroundTimer = new Timer();
                appBackgroundTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        boolean change = false;
                        if(!lastAppForeground){
                            change = true;
                        }
                        lastAppForeground = true;
                        Log.e(TAG, "发送app处于前台的消息");
                        Intent intent = new Intent();
                        intent.setAction(BC_IS_FOREGROUND);
                        intent.putExtra(DATA_IS_FOREGROUND, true);
                        intent.putExtra(DATA_IS_FOREGROUND_CHANGED, change);
                        sendBroadcast(intent);
                    }
                }, 800);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                isAppInForeground = false;
                Log.e(TAG, "后台");
                if(appBackgroundTimer!=null){
                    appBackgroundTimer.cancel();
                    appBackgroundTimer = null;
                }
                appBackgroundTimer = new Timer();
                appBackgroundTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        boolean change = false;
                        if(lastAppForeground){
                            change = true;
                        }
                        lastAppForeground = false;
                        Log.e(TAG, "发送app处于后台的消息");
                        Intent intent = new Intent();
                        intent.setAction(BC_IS_FOREGROUND);
                        intent.putExtra(DATA_IS_FOREGROUND, false);
                        intent.putExtra(DATA_IS_FOREGROUND_CHANGED, change);
                        sendBroadcast(intent);
                    }
                }, 800);
            }

            @Override
            public void onActivityStopped(Activity activity) {}

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

            @Override
            public void onActivityDestroyed(Activity activity) {}
        });
    }

    public static boolean isAppInForeground(){
        return isAppInForeground;
    }
}
